<template>
  <el-dialog :visible.sync="visible" :before-close="function(){$emit('closeDialog')}" fullscreen>
    <el-card
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      :header="(form.roleid?'编辑':'新增')+'角色'"
      shadow="always"
    >
      <el-form
        v-if="show"
        label-position="top"
        v-loading="loading"
        ref="form"
        :model="form"
        label-width="100px"
        inline
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名:" prop="roleName">
              <el-input style="width: 400px;" v-model="form.rolename"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色状态:" prop="roleName">
              <el-switch
                v-model="form.rolestatus"
                active-value="1"
                inactive-value="0"
                active-text="启用"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-form-item label="角色权限:">
            <el-button type="primary" plain @click="checkAll">全选</el-button>
            <table
              style="width:60%"
              class="gridtable"
              :key="index"
              v-for="(item,index) in authTree"
              border="1"
            >
              <tr>
                <th
                  v-if="item.status == 1"
                  :class="checkedCases[item.moduleID].isChecked ? 'blue': ''"
                  :colspan="item.child?item.child.length:0"
                >
                  <el-checkbox
                    @change="onChange($event, item)"
                    v-model="checkedCases[item.moduleID].isChecked"
                    style="margin-left: 0px;white-space: normal;"
                    :label="item.moduleID"
                  >{{item.moduleName}}</el-checkbox>
                </th>
              </tr>
              <tr>
                <td
                  v-for="(childitem,childindex) in item.child"
                  :key="childindex"
                  :class="checkedCases[item.moduleID]['child'][childitem.moduleID].isChecked ? 'blue': ''"
                >
                  <el-checkbox
                    v-if="checkVisable && childitem.status == 1"
                    v-model="checkedCases[item.moduleID]['child'][childitem.moduleID].isChecked"
                    style="margin-left: 0px;white-space: normal;"
                    @change="onChangeSub($event, childitem.moduleID, item.moduleID)"
                    :label="childitem.moduleID"
                  >{{childitem.moduleName}}</el-checkbox>
                </td>
              </tr>
            </table>
          </el-form-item>
        </el-row>
      </el-form>
      <el-row type="flex" justify="center" style="margin-top: 50px">
        <el-col :span="4">
          <el-button @click="$emit('closeDialog')">取消</el-button>
          <el-button
            type="primary"
            @click="onSubmit"
            plain
          >{{ form.roleid !== "" ? '确认编辑' : '确认添加' }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: Boolean,
    editData: Array
  },
  data() {
    return {
      form: {
        rolename: "",
        rolestatus: "",
        roledescription: "",
        roleremarks: ""
      },
      show: true,
      loading: false,
      options: [],
      rules: {
        roleName: [{ required: true, message: "请输入角色名", trigger: "blur" }]
      },
      authTree: [],
      checkedCases: {},
      roleModules: [],
      roleCases: [],
      moduleCaseMap: {},
      parentModuleMap: {},
      checkedList: [],
      checkVisable: true,
      isCheckAll: false
    };
  },
  mounted() {
    this.fetchAllAuth();
  },
  methods: {
    async onSubmit() {
      try {
        let res = null;
        let data = this.form;
        let permission = [];
        console.log(this.checkedCases);
        //debugger;
        for (let item in this.checkedCases) {
          this.checkedCases[item].isChecked ? permission.push(item) : "";
          for (let subItem in this.checkedCases[item].child) {
            if (this.checkedCases[item].child[subItem].isChecked) {
              permission.push(subItem);
              if (this.checkedCases[item].isChecked === false && !permission.includes(item)) {
                permission.push(item);
              }
            }
          }
        }
        //console.log(permission);
        //debugger;
        let form = {
          rolename: this.form.rolename,
          rolestatus: this.form.rolestatus,
          modules: permission.join(",")
        };
        //console.log(form);
        this.form.roleid === ""
          ? (res = await this.$api.post(
              `http://139.9.249.149:8081/judge/role`,
              form,
              { autoAlert: false, returnAll: true }
            )) //新增
          : (res = await this.$api.put(
              `http://139.9.249.149:8081/judge/role`,
              { ...form, roleid: this.form.roleid },
              { autoAlert: false, returnAll: true }
            ));
        this.$openMsg(res);
        if (res.code == 200) {
          this.$emit("closeDialog");
        } else throw "fail";
      } catch (e) {
        this.$message.error("操作失败");
        console.log(e);
      }
    },
    onChange(data, item) {
      item.child.map(subItem => {
        // if (data) !this.checkedCases[item.moduleID].child[subItem.moduleID] ? this.checkedCases[subItem.moduleID] = true : '';
        // else this.checkedCases[subItem.moduleID] = false;
        this.checkedCases[item.moduleID].child[
          subItem.moduleID
        ].isChecked = data;
        this.checkVisable = false;
        this.$nextTick(() => {
          this.checkVisable = true;
        });
      });
    },
    onChangeSub() {
      this.checkVisable = false;
      this.$nextTick(() => {
        this.checkVisable = true;
      });
    },
    checkAll() {
      this.isCheckAll = !this.isCheckAll;
      for (let item in this.checkedCases) {
        this.checkedCases[item].isChecked = this.isCheckAll;
        for (let subItem in this.checkedCases[item].child) {
          this.checkedCases[item].child[subItem].isChecked = this.isCheckAll;
        }
      }
      this.checkVisable = false;
      this.$nextTick(() => {
        this.checkVisable = true;
      });
    },
    clearAllCheckedCases() {
      for (let i in this.checkedCases) {
        this.checkedCases[i].isChecked = false;
        for (let j in this.checkedCases[i]["child"]) {
          this.checkedCases[i]["child"][j];
          this.checkedCases[i]["child"][j].isChecked = false;
        }
      }
    },
    async fetchAllAuth() {
      try {
        const res = await this.$api.get(
          //获取权限树
          `/module`,
          {},
          { autoAlert: false, returnAll: true }
        );
        this.authTree = res.data.msg;
        this.authTree.forEach(item => {
          this.checkedCases[item.moduleID] = {
            isChecked: false,
            child: {}
          };
          item.child.forEach(subItem => {
            this.checkedCases[item.moduleID].child[subItem.moduleID] = {
              isChecked: false,
              child: {}
            };
          });
        });
        //console.log(this.checkedCases);
      } catch (e) {
        console.log(e);
      }
    }
  },
  watch: {
    visible: {
      async handler(data) {
        //console.log(this.editData);
        this.clearAllCheckedCases();
        if (data && this.editData.length !== 0) {
          for (let module of this.editData[0].modules) {
            //勾选对应的选项
            try {
              if (this.checkedCases[module] != undefined) {
                //判断是否是父模块
                // this.checkedCases[module].isChecked = true;
              } else {
                //不是的话遍历勾选子模块
                for (let item in this.checkedCases) {
                  if (
                    this.checkedCases[item]["child"] != undefined && //判断是否有子模块
                    this.checkedCases[item]["child"][module] != undefined //如果有子模块，看是否拥有对应模块
                  ) {
                    this.checkedCases[item]["child"][module].isChecked = true;
                  }
                }
              }
            } catch (error) {
              console.log(error);
            }
          }
          this.form.rolename = this.editData[0].rolename;
          this.form.rolestatus = this.editData[0].rolestatus;
          this.form.roleid = this.editData[0].roleid;
        }
        this.show = false;
        this.$nextTick(() => {
          this.show = true;
        });
      },
      immediate: false
    }
  }
  // created() {
  //   this.fetchAllAuth();
  // }
};
</script>

<style scoped lang="stylus">
.gridtable {
  font-family: verdana, arial, sans-serif;
  font-size: 11px;
  color: #333333;
  border-width: 1px;
  border-color: #ebeef5;
  border-collapse: collapse;
  table-layout: fixed;
  margin-top: 10px;

  th {
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #ebeef5;
  }

  td {
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #ebeef5;
    background-color: #ffffff;
  }
}

.blue {
  background-color: #bbe1fa;
}
</style>
